import React from 'react'
import { findDOMNode } from 'react-dom'

class List extends React.Component {
  constructor (props) {
    super(props)
    // props.domScroll 监听滚动时间的容器，body || this.refs.xxx
    // props.domLoading 底部loading元素，自定义
    // props.bottom 距离屏幕底部多少距离触发onLoad，number
    // props.isLoading 加载数据中，true || false
    // props.isFinish 是否结束加载更多，true || false
    // props.onLoad 滑动到底部触发时间，function(){}
  }

  componentDidMount () {
    this.onAddScroll()
  }

  // 绑定滚动
  onAddScroll = () => {
    const dom = this.props.domScroll
    if (dom === 'body') {
      document.body.addEventListener('scroll', this.onLoad)
    } else {
      findDOMNode(dom).addEventListener('scroll', this.onLoad)
    }
  }

  // 解绑滚动
  onRemoveScroll = () => {
    const dom = this.props.domScroll
    if (dom === 'body') {
      document.body.removeEventListener('scroll', this.onLoad)
    } else {
      findDOMNode(dom).removeEventListener('scroll', this.onLoad)
    }
  }

  // 上滑加载更多
  onLoad = () => {
    const main = findDOMNode(this.refs.Main)
    const bottom = Number(this.props.bottom || 0)
    const isLoad = main.getBoundingClientRect().bottom - bottom <= window.innerHeight
    // 滚动到底部，未在加载中，未加载完列表数据
    if (isLoad && !this.props.isLoading && !this.props.isFinish) {
      this.props.onLoad()
    }
    if (this.props.isFinish) {
      this.onRemoveScroll()
    }
  }

  render () {
    return (
      <div
        ref='Main'
        style={{ width: '100%', overflow: 'hidden', margin: 0, padding: 0 }}
      >
        {this.props.children}
        {this.props.isFinish === false && this.props.domLoading}
      </div>
    )
  }
}

export default List
